package cn.edu.sdjzu.xg.bysj.dao;

import cn.edu.sdjzu.xg.bysj.domain.User;
import util.JdbcHelper;

import java.sql.*;
import java.util.Collection;


public final class UserDao {
    private static UserDao userDao = new UserDao();
    private static Collection<User> users;


    private UserDao() {
    }

    public static UserDao getInstance() {
        return userDao;
    }

    public static void main(String[] args) {
        UserDao dao = new UserDao();
        Collection<User> users = dao.findAll();
        display(users);
    }

    private static void display(Collection<User> users) {
        for (User user : users) {
            System.out.println(user);
        }
    }

    public Collection<User> findAll() {
        return UserDao.users;
    }

//    public static User find(int id) throws SQLException {
//        Connection connection = JdbcHelper.getConn();
//        //创建sql语句
//        String find_sql = "select * from user where id = ?";
//        //在该连接上创建预编译语句对象
//        PreparedStatement pstmt = connection.prepareStatement(find_sql);
//        //为预编译参数赋值
//        pstmt.setInt(1, id);
//        //创建结果集对象
//        ResultSet resultSet = pstmt.executeQuery();
//        //游标下移
//        resultSet.next();
//        //创建Teacher对象，各字段为结果集中相应字段
//        User user = new User(resultSet.getInt("id"),
//                resultSet.getString("username"),
//                resultSet.getString("password"),
//                resultSet.getTimestamp("lastLoginTime").toLocalDateTime(),
//                ActorDao.find(resultSet.getInt("teacher_id"),connection)
//
//        );
//        JdbcHelper.close(resultSet, pstmt, connection);
//        return user;
//    }

    public boolean update(User user) {
        users.remove(user);
        return users.add(user);
    }

    public boolean add(User user, Connection connection)throws SQLException {
        //创建语句对象，字段lastLoginTime为“时间戳”类型，无需手动写入
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO user(username,password,actor_id)"+
                "VALUES (?,?,?)", Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1,user.getUsername());
        preparedStatement.setString(2,user.getPassword());
        preparedStatement.setInt(3,user.getStudent().getId());
        //执行语句
        int rowAffected =preparedStatement.executeUpdate();
        //事务未结束，不能释放资源
        int idOfAddedUser = 0;
        //获得生成的主键集合
        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        if (resultSet.next()) {
            //读取第一个
            idOfAddedUser = resultSet.getInt(1);
        }
        JdbcHelper.close(null,preparedStatement);
        return rowAffected>0;

    }

//    public boolean delete(Integer id)throws SQLException {
//        User user = this.find(id);
//        return this.delete(user);
//    }
//
//    public boolean delete(User user) {
//        return users.remove(user);
//    }


}